<template>
	<div id="app">
		<router-view />
	</div>
</template>

<script>
import eventbus from '@/utils/eventbus'
import { getVoiceConfig } from '@/api/qbs/speech'
const WEBSOCKET_RECONNECT_TIMEOUT = 10000
export default {
	name: 'App',
	data() {
		return {
			webSocket: null,
			url: '',
			reconnectTimeout: null, // 定时器
		}
	},
	computed: {},
	async created() {
		const { data } = await getVoiceConfig()
    console.log(`getVoiceConfig`,data)
		this.$store.state.user.serverPort = data.ip + ":" + data.serverPort
		this.$store.state.user.staticPort = data.ip + ":" + `${data.staticPort}`
		this.url = data.address
		// 页面打开就建立连接，根据业务需要
		this.initSocket()
	},
	destroyed() {
		// 页面销毁关闭连接
		this.closeSocket()
	},
	methods: {
		initSocket() {
			// 有参数的情况下：
			// const url = `ws://${window.location.host}/ws`
			const url = `ws://${this.url}/ws`
			console.log(`连接地址`, url)
      		this.closeSocket({ reconnect: false });
			this.webSocket = new WebSocket(url)
			this.webSocket.reconnect = true
			this.webSocket.onopen = this.webSocketOnOpen
			this.webSocket.onclose = this.webSocketOnClose
			this.webSocket.onmessage = this.webSocketOnMessage
			this.webSocket.onerror = this.webSocketOnError
		},
		closeSocket({ reconnect = true } = {}) {
			if (this.webSocket) {
				if (this.reconnectTimeout) {
					clearTimeout(this.reconnectTimeout);
					this.reconnectTimeout = null;
				}
				this.webSocket.reconnect = reconnect;
				this.webSocket.close();
			}
		},
		// 建立连接成功后的状态
		webSocketOnOpen() {
			console.log('websocket连接成功')
			this.$store.dispatch('NettyStatus', true)
		},
		// 获取到后台消息的事件，操作数据的代码在onmessage中书写
		webSocketOnMessage(res) {
			// res就是后台实时传过来的数据
			console.log(res)
			let JSONdata = JSON.parse(res.data)
			if(JSONdata.type =='121' /*后端定义常量消息结构：网页授权消息*/){
				this.$message({
					message:JSONdata.payload.msg,
					type: 'warning',
				})
			}
			if (JSONdata.type == '120' /*后端定义常量消息结构：给web发送弹窗消息*/) {
				this.$message({
					message: JSONdata.payload.msg,
					type: 'warning',
				})
			}
			eventbus.$emit('websocket', JSONdata || '')
		},
		// 关闭连接
		webSocketOnClose() {
			console.log('websocket连接已关闭')
			this.$store.dispatch('NettyStatus', false)
			if (!this.webSocket.reconnect) {
				// 重连
				if (this.reconnectTimeout) clearTimeout(this.reconnectTimeout);
				this.reconnectTimeout = setTimeout(() => {
					console.log('websocket正在重连');
					this.initSocket()
				}, WEBSOCKET_RECONNECT_TIMEOUT);
			}
		},
		// 连接失败的事件
		webSocketOnError(res) {
      		console.log('websocket连接失败', res);
			// 关闭重连
      		this.webSocket.close();
		},
	},
}
</script>
<style lang="scss">
#app {
	width: 100%;
	height: 100%;
	overflow: hidden;
}
</style>
